package com.esteel.settlement.config.pa;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import com.esteel.settlement.pa.packet.PaPacket;

/**
 * 获得交易报文的公共接口
 * @author zhangxiuzhi
 *
 */
public class PacketFactory {
	
	@Autowired
	private PaAcctIdProperties acct;

	public <T> T getPacket(Class<T> packetClass){
		Assert.isAssignable(PaPacket.class, packetClass);
		try {
			T result = packetClass.newInstance();
			
			PaPacket packet = (PaPacket)result;
			packet.setCounterId(acct.getCounterId());
			packet.setQydm(acct.getTranWebCode());
			packet.setTransDate(new Date());
			packet.setServType(PaPacket.REQUEST);
			
			setValue(packet,"ccyCode","RMB");
			setValue(packet,"supAcctId",acct.getAcctId());
			setValue(packet,"acctId",acct.getAcctId());
			setValue(packet,"tranWebName",acct.getTranWebName());
			setValue(packet,"tranWebCode",acct.getTranWebCode());
			
			return result;
		} catch (InstantiationException | IllegalAccessException e) {
		
			e.printStackTrace();
		}
		return null;
	}
	
	
	private void setValue(Object target ,String fieldName,Object value){
		fieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

		try {
			Method method = target.getClass().getMethod("set" + fieldName, value.getClass());
			if (method!=null){
				method.invoke(target, value);
			}
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
	
		}
	}
}
